<?php
namespace Api\Controller;

class CartController extends ApiController
{

    /**
     * 加入购物车
     * 
     * @param
     *            int product_id
     * @param
     *            int quantity
     * @param
     *            double price
     */

    public function addTocart()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array(
            'product_id',
            'quantity',
            'option_ids'
        ));
        $data = params_post(array(
            'product_id',
            'quantity',
            'option_ids'
        ));
        $M_product = M("product");
        $M_cart = M('cart');
        $M_producdt_option_price = M('product_option_price');
        $M_product_option = M('product_option');
        ! preg_match('/^[1-9]\d*$/', $data['quantity']) && response(- 1, '数量错误');
        $product_info = $M_product->where(array('id'=>$data['product_id'],'status'=>1))->find();
        $product_info || response(-2, null, '商品不存在或已下架');
        $data['price'] = $product_info['price'];
        if ($data['option_ids']) {
            ! get_table_field($data['option_ids'], 'product_option_id', 'price', 'product_option_price') && response(- 1, '', '不存在的组合价格');
        }
        $option_price = get_table_field($data['option_ids'], 'product_option_id', 'price', 'product_option_price');

        if (! $data['option_ids']) {
            $data['product_attr'] = '默认';
            $data['option_ids'] = 0;
        } else {
            $product_attr_text = '';
            $product_option_id = explode(',', $data['option_ids']);
            foreach ($product_option_id as $key => $value) {
                $tem_pid = get_table_field($value, 'id', 'pid', 'product_option');
                $product_attr_text .= get_table_field($tem_pid, 'id', 'title', 'product_option') . ':';
                $product_attr_text .= get_table_field($value, 'id', 'title', 'product_option') . ',';
            }
            $data['product_attr'] = substr($product_attr_text, 0, strlen($product_attr_text) - 1);
        }

        $map = array(
            'product_id' => $data['product_id'],
            'uid' => API_UID,
            'status' => 1,
            'option_ids' => $data['option_ids']
        );

        ! get_table_field($data['product_id'], 'id', 'id', 'product') && response(- 2, '', '商品不存在');

        ! (is_numeric($data['price']) && $data['price'] > 0) && $this->error('商品价格错误，不能小于1');

        $data['total_price'] = $data['price'] * (int) $data['quantity'];
        $data['uid'] = API_UID;
        $data['create_time'] = NOW_TIME;
        $data['update_time'] = NOW_TIME;
        $data['status'] = 1;
        $exist = $M_cart->where($map)->find();
        $result = 0;
        if ($exist) {
            $result = $M_cart->where($map)->setInc('quantity', $data['quantity']);
            $M_cart->where($map)->setInc('total_price', $data['price']);
        } else {
            $result = $M_cart->add($data);
        }
        $result <= 0 && response(- 2);
        response(1);
    }

    /**
     * 删除购物车项
     * 
     * @param
     *            int cart_id
     */
    public function delCartbyId()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array(
            'cart_id'
        ));
        
        $M_cart = M('cart');
        $cart_id = I('post.cart_id');
        
        ! $M_cart->where(array(
            'id' => $cart_id,
            'uid' => API_UID
        ))->find() && response(- 2, '', '不存在的购物车');
        
        $M_cart->where(array(
            'id' => $cart_id
        ))->setfield('status', 0) !== false ? response(1) : response(- 9);
    }

    /**
     * 编辑 购物车
     * 
     * @param
     *            int cart_id
     * @param
     *            int quantity
     * @param
     *            double price
     */
    public function editCart()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array(
            'cart_id',
            'quantity',
            'price',
            'option_ids'
        ));
        
        $data = params_post(array(
            'cart_id',
            'quantity',
            'price',
            'option_ids'
        ));
        $data['update_time'] = NOW_TIME;
        
        $M_producdt_option_price = M('product_option_price');
        $M_product_option = M('product_option');
        $M_product = M("product");
        $M_cart = M('cart');
        
        ! $M_cart->where(array(
            'id' => $data['cart_id'],
            'uid' => API_UID
        ))->find() && response(- 2, '', '不存在的购物车');
        
        if ($data['option_ids']) {
            ! get_table_field($data['option_ids'], 'product_option_id', 'price', 'product_option_price') && response(- 1, '', '不存在的组合价格');
        }
        $option_price = get_table_field($data['option_ids'], 'product_option_id', 'price', 'product_option_price');
        if ($option_price) {
            (double) $data['price'] != $option_price && response(- 1, '', '组合价格错误' . $option_price);
        }
        if (! $data['option_ids']) {
            $data['product_attr'] = '默认';
            $data['option_ids'] = 0;
        } else {
            $product_attr_text = '';
            $product_option_id = explode(',', $data['option_ids']);
            foreach ($product_option_id as $key => $value) {
                $tem_pid = get_table_field($value, 'id', 'pid', 'product_option');
                $product_attr_text .= get_table_field($tem_pid, 'id', 'title', 'product_option') . ':';
                $product_attr_text .= get_table_field($value, 'id', 'title', 'product_option') . ',';
            }
            $data['product_attr'] = substr($product_attr_text, 0, strlen($product_attr_text) - 1);
        }
        $data['total_price'] = (double) $data['price'] * (int) $data['quantity'];
        
        ! (preg_match('/^[\d]+$/', $data['quantity']) && (int) ($data['quantity']) > 0) && response(- 1, '', '商品数量不能小于0');
        
        ! (is_numeric($data['price']) && (double) $data['price'] > 0) && $this->error('商品价格错误，不能小于1');
        
        $result = $M_cart->where(array(
            'id' => $data['cart_id']
        ))->save($data);
        
        $result !== false ? response(1) : response(- 1);
    }

    /**
     * 加入订单
     * 
     * @param
     *            int cart_id[]
     */
    public function toTrade()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array('cart_id'));
        $cart_id = I('post.cart_id');
        empty($cart_id) && response(- 1, '', '参数错误');
        is_array($cart_id) || $cart_id = str2arr($cart_id, ',');
        
        $carts = M('cart')->where(array('uid'=>API_UID, 'id'=>array('in',$cart_id)))->select();
        $carts || response(-2, null, '购物车项为空');

        $shop = array();
        foreach ($carts as $cart) {

            $total_price = $cart['quantity']*$cart['price'];

            $product_info = M('product')->find($cart['product_id']);
            $product_info || response(-1, null, '找不到商品');
            $product_info['status'] == 1 || response(-1, null, '商品已下架');
            
            
            $index = 'shop_' . $product_info['shop_id'];
            if (!isset($shop[$index])) {
                $shop_info = M('shop')->find($product_info['shop_id']);
                $shop[$index]['shop_id'] = $shop_info['id'];
                $shop[$index]['shop_title'] = $shop_info['title'];
            }
            //获取商品选项价格
            $product_price = $product_info['price'];
            if ($cart['option_ids']) {
                $product_option_price = M('product_option_price')->where(array('product_id'=>$cart['product_id'], 'product_option_id'=>$cart['option_ids']))->find();
                $product_option_price && $product_price = $product_option_price['price'];
            }
            $product_total_price = $product_price * intval($cart['quantity']);
            
            //判断商品是不是在抢购会
            if ($product_info['in_special_panic']) {
                $product_panic_info = M('product_special_panic')->where(array('product_id'=>$cart['product_id']))->find();
                $special_panic_info = M('special_panic')->where(array('id'=>$product_panic_info['special_panic_id'], 'status'=>1))->find();

                if ($special_panic_info) {
                    $special_panic_result_starttime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_info['start_time']));
                    $special_panic_result_endtime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_info['end_time']));
                    if(($special_panic_result_starttime<=NOW_TIME) && ($special_panic_result_endtime>= NOW_TIME)){
                        if ($total_price >= $product_panic_info['condition_price']) {
                            $product_price = $product_price * $product_panic_info['discount'] * 0.1;
                            $total_price = $product_price * $cart['quantity'];
                        }
                    }
                }
            }
            
            $images = M('product_image')->where(array('product_id'=>$product_info['id']))->find();
            $images = array('id'=>$images['cover_id'], 'path'=>get_url($images['cover_id']));
            $cartItem = array(
                'cart_id' => $cart['id'],
                'product_id' => $product_info['id'],
                'title' => $product_info['title'],
                'price' => $product_price,
                'quantity' => $cart['quantity'],
                'total_price' => $total_price,
                'option_ids' => $cart['option_ids'],
                'product_attr' => $cart['product_attr'],
                'images' => $images
            );
            $total_price += $cartItem['total_price'];
            $shop[$index]['product'][] = $cartItem;
        }
        shuffle($shop);
        response(1, $shop);
    }

    /**
     * 获取购物车
     * 
     * @param
     *            int page
     * @param
     *            int page_size
     */
    public function getCarts()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $page = I('post.page', 1);
        $page_size = I('post.page_size', 5);
        $offset = ($page - 1) * $page_size;
        
        $M_product_image = M('product_image');
        $M_shop = M('shop');
        
        $prefix = C('DB_PREFIX');
        $l_table = $prefix . ('product');
        $r_table = $prefix . ('cart');
        
        $model = M('cart');
        
        $model = $model->table($l_table . ' l')->join($r_table . ' r on r.product_id=l.id');
        
        $options['field'] = array(
            'l.title ',
            'l.shop_id',
            'l.category_id',
            'l.uid seller_uid',
            'l.in_special_panic',
            'r.price',
            'l.price product_price',
            'r.total_price',
            'r.product_id ',
            'r.id cart_id',
            'r.quantity',
            'r.uid',
            'r.status',
            'r.option_ids'
        );
        $OPT = new \ReflectionProperty($model, 'options');
        $OPT->setAccessible(true);
        
        $map = array();
        $map['r.uid'] = API_UID;
        $map['r.status'] = 1;
        $options['order'] = 'r.id DESC';
        $options['where'] = $map;
        
        $options = array_merge((array) $OPT->getValue($model), $options);
        $total = $model->where($options['where'])->count();
        $model->setProperty('options', $options);
        
        $carts_list = $model->limit($offset, $page_size)->select();
        $cart_result = array();
        foreach ($carts_list as $ca_item) {
            $price = $ca_item['product_price'];
            if ($ca_item['option_ids']) {
                $product_option_price = M('product_option_price')->where(array('product_id'=>$ca_item['product_id'], 'product_option_id'=>$ca_item['option_ids']))->find();
                $product_option_price && $price = $product_option_price['price'];
            }
            $total_price = $price * intval($ca_item['quantity']);
            if ($ca_item['in_special_panic']) {
                $product_panic_info = M('product_special_panic')->where(array('product_id'=>$ca_item['product_id']))->find();

                $special_panic_info = M('special_panic')->where(array('id'=>$product_panic_info['special_panic_id'], 'status'=>1))->find();
                // $special_panic_info = M('special_panic')->where(array('id'=>$product_panic_info['special_panic_id'], 'status'=>1, 'start_time'=>array('elt',NOW_TIME), 'end_time'=>array('egt',NOW_TIME)))->find();

                if ($special_panic_info) {
                    $special_panic_result_starttime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_info['start_time']));
                    $special_panic_result_endtime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_info['end_time']));
                    if(($special_panic_result_starttime<=NOW_TIME) && ($special_panic_result_endtime>= NOW_TIME)){
                        if ($total_price >= $product_panic_info['condition_price']) {
                            $price = $price * $product_panic_info['discount'] * 0.1;
                            $total_price = $price * $ca_item['quantity'];
                        }
                    }
                }
	            




                // if ($special_panic_info) {
                //     if ($product_panic_info['condition_price'] > 0) {
                //         $total_price >= $product_panic_info['condition_price'] && $price = $price * $product_panic_info['discount'] / 10;
                //     } else {
                //         $price = $price * $product_panic_info['discount'] / 10;
                //     }
                //     $total_price = $price * $ca_item['quantity'];
                // }
            }
            
            $tem_shop = $M_shop->find($ca_item['shop_id']);
            $tem_cart_item = array();
            $tem_cart_item['cart_id'] = $ca_item['cart_id'];
            $tem_product = array();
            $tem_product['title'] = $ca_item['title'];
            $tem_product['total_price'] = $total_price;
            $tem_product['price'] = $price;
            $tem_product['quantity'] = $ca_item['quantity'];
            $tem_product['product_id'] = $ca_item['product_id'];
            $tem_product['option_ids'] = $ca_item['option_ids'];
            $tem_product['category_id'] = $ca_item['category_id'];
            $tem_product['product_price'] = $ca_item['product_price'];
            $tem_product['cart_id'] = $ca_item['cart_id'];
            
            $images = $M_product_image->where(array('product_id' => $ca_item['product_id']))->find();
            $tem_product['image_path'] = get_url($images['cover_id']);
            
            if ($tem_shop) {
                $tem_cart_item['shop_id'] = $ca_item['shop_id'];
                $tem_cart_item['shop_title'] = $tem_shop['title'];
                $index = 'shop_' . $ca_item['shop_id'];
            } else {
                $tem_cart_item['shop_id'] = 0;
                $tem_cart_item['shop_title'] = get_username($ca_item['seller_uid']);
                $index = 'user_' . $ca_item['seller_uid'];
            }
            isset($cart_result[$index]) || $cart_result[$index] = $tem_cart_item;
            $cart_result[$index]['product'][] = $tem_product;
        }
        shuffle($cart_result);
        $result['result'] = $cart_result;
        $result['total'] = $total;
        
        response(1, $result);
    }
}
?>
